﻿using System;
using System.Web.Mvc;

namespace Fuse8.ContentManagementFramework.Web.MvcPowered
{
    public class CmsPreviewRazorViewEngine: RazorViewEngine
    {
        #region Consts

        public static readonly string PreviewTemplatePath = "~/admin/Views/_Preview.cshtml";
        public static readonly string PreviewTemplateFileName = "_ViewStart";

        #endregion 

        #region Singleton

        private static readonly object _syncRoot = new object();
        private static volatile CmsPreviewRazorViewEngine _instance;

        public static CmsPreviewRazorViewEngine GetInstance()
        {
            if (_instance == null)
            {
                lock (_syncRoot)
                {
                    if (_instance == null)
                    {
                        _instance = new CmsPreviewRazorViewEngine();
                    }
                }
            }

            return _instance;
        }

        #endregion

        public CmsPreviewRazorViewEngine()
            : base()
        { }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            return new RazorView(controllerContext, viewPath, masterPath, true, null, null);
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            return new ViewEngineResult(CreateView(controllerContext, PreviewTemplatePath, masterName), this);
        }
    }
}
